package com.yxq.mdt.app.modules.personal.ui.anchor;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.modules.bean.UploadImageBean;
import com.yxq.mdt.app.modules.personal.bean.FaceCheckResult;
import com.yxq.mdt.app.modules.personal.bean.RealNameResultBean;
import com.yxq.mdt.app.modules.personal.model.RealNameModel;
import com.yxq.mdt.app.modules.personal.presenter.IRealNameContract;
import com.yxq.mdt.app.modules.personal.presenter.RealNamePresenter;
import com.yxq.mdt.app.modules.socialcontact.adapter.PublishImageListAdapter;
import com.yxq.mdt.app.net.API;
import com.yxq.mdt.app.utils.GlideEngine;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;
import com.yxq.mdt.app.modules.webview.ui.MiWebViewActivity;
import com.yxq.mdt.app.utils.StringUtils;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 编辑认证界面
 */
public class PersonalRealEditNameAc extends BaseActivity<RealNamePresenter> implements IRealNameContract.View {
    @BindView(R.id.write_ed_name)
    EditText writeEdName;
    @BindView(R.id.write_ed_number)
    EditText writeEdNumber;
    @BindView(R.id.write_ed_number_btn)
    Button writeEdNumberBtn;
    @BindView(R.id.write_check)
    CheckBox writeCheck;
    @BindView(R.id.anchor_tv_user)
    TextView anchorTvUser;
    @BindView(R.id.anchor_tv_privacy)
    TextView anchorTvPrivacy;
    @BindView(R.id.write)
    LinearLayout write;
    @BindView(R.id.publish_img_recyclerView)
    RecyclerView publishImgRecyclerView;
    List<UploadImageBean> uploadImageBeanList;
    PublishImageListAdapter uploadImageListAdapter;
    List<LocalMedia> images;

    @Override
    public int getLayoutId() {
        return R.layout.layout_write_real_name;
    }

    @Override
    public void initView() {
        //初始化图片上传控件
        publishImgRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        uploadImageBeanList = new ArrayList<>();
        uploadImageBeanList.add(new UploadImageBean());
        uploadImageListAdapter = new PublishImageListAdapter(uploadImageBeanList);
        publishImgRecyclerView.setAdapter(uploadImageListAdapter);
        publishImgRecyclerView.addItemDecoration(new GridSpacingItemDecoration(3, 5, false));
        uploadImageListAdapter.setOnItemClickListener((adapter, view, position) -> {

            if (uploadImageListAdapter.getItem(position).getItemType() == -1) {
                selectImages();
            } else {
                //预览图片
                PictureSelector.create(mActivity).externalPicturePreview(position, images,1);
            }
        });
        uploadImageListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            List<UploadImageBean> uploadImageBeanList = uploadImageListAdapter.getData();
            if (uploadImageBeanList.get(uploadImageBeanList.size() - 1).getItemType() != -1) {
                uploadImageBeanList.remove(position);
                //第一张不是添加图片，添加按钮
                List<UploadImageBean> temp = new ArrayList<>();
                temp.addAll(uploadImageBeanList);
                temp.add(new UploadImageBean());
                uploadImageListAdapter.setNewData(temp);
            } else {
                uploadImageListAdapter.remove(position);
            }
        });
    }

    /**
     * 打开图片选择器
     */
    private void selectImages() {
        //相册
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(2 - uploadImageListAdapter.getData().size())//最大选择数目 最大6张减去现在已经添加的张数
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.MULTIPLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new RealNamePresenter(this, new RealNameModel());
        showLoadingDialog();
        mPresenter.getCardNoAndName();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    //compressPath 压缩图片地址
                    // 图片选择结果回调
                    images = PictureSelector.obtainMultipleResult(data);
                    parseLocalMedia(images);
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + requestCode);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 填充图片到界面
     *
     * @param images
     */
    private void parseLocalMedia(List<LocalMedia> images) {
        List<UploadImageBean> data = new ArrayList<>();
        UploadImageBean uploadImageBean;
        for (LocalMedia localMedia : images) {
            uploadImageBean = new UploadImageBean();
            uploadImageBean.setItemType(0);
            uploadImageBean.setPath(localMedia.getCompressPath());
            data.add(uploadImageBean);
        }
        List<UploadImageBean> temp = uploadImageListAdapter.getData();
        temp.remove(temp.size() - 1);
        temp.addAll(data);
        temp.add(new UploadImageBean());
        uploadImageListAdapter.setNewData(temp);

        if (uploadImageListAdapter.getData().size() == 2) {
            uploadImageListAdapter.getData().remove(1);
        }
        uploadImageListAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.write_ed_number_btn, R.id.anchor_tv_user, R.id.anchor_tv_privacy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.write_ed_number_btn:
                if (!writeCheck.isChecked()) {
                    ToastUtils.showShort("请先阅读并同意相关协议");
                    return;
                }
                if (writeEdName.getText().toString().length() == 0) {
                    ToastUtils.showShort("请输入身份证上的姓名");
                    return;
                }
                if (writeEdNumber.getText().toString().length() == 0) {
                    ToastUtils.showShort("请输入身份证上的号码");
                    return;
                }
                if (images == null) {
                    ToastUtils.showShort("请上传包含个人人脸的照片");
                    return;
                }
                if (images.size() == 0) {
                    ToastUtils.showShort("请上传包含个人人脸的照片");
                    return;
                }
                certification();
                break;
            case R.id.anchor_tv_user:
                Intent intent = new Intent(mActivity, MiWebViewActivity.class);
                intent.putExtra("url", API.USER_AGREEMENT);
                intent.putExtra("title", "用户协议");
                startActivity(intent);
                break;
            case R.id.anchor_tv_privacy:
                intent = new Intent(mActivity, MiWebViewActivity.class);
                intent.putExtra("url", API.PRIVACY_POLICY);
                intent.putExtra("title", "隐私协议");
                startActivity(intent);
                break;
        }
    }

    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
//        if (host.startsWith("https://")) {
//            sslClient(httpClient);
//        }

        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
//        try {
//            SSLContext ctx = SSLContext.getInstance("TLS");
//            X509TrustManager tm = new X509TrustManager() {
//                @Override
//                public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
//
//                }
//
//                @Override
//                public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
//
//                }
//
//                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
//                    return null;
//                }
//            };
//            ctx.init(null, new TrustManager[]{tm}, null);
//            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
//            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
//            ClientConnectionManager ccm = httpClient.getConnectionManager();
//            SchemeRegistry registry = ccm.getSchemeRegistry();
//            registry.register(new Scheme("https", ssf, 443));
//        } catch (KeyManagementException ex) {
//            throw new RuntimeException(ex);
//        } catch (NoSuchAlgorithmException ex) {
//            throw new RuntimeException(ex);
//        } catch (UnrecoverableKeyException e) {
//            e.printStackTrace();
//        } catch (KeyStoreException e) {
//            e.printStackTrace();
//        }
    }

    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isEmpty(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isEmpty(query.getKey()) && !StringUtils.isEmpty(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isEmpty(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isEmpty(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    /**
     * post form
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param bodys
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      Map<String, String> bodys) {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = null;
        try {
            request = new HttpPost(buildUrl(host, path, querys));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = null;
            try {
                formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        try {
            return httpClient.execute(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 实名认证
     */
    private void certification() {
        showLoadingDialog();
        String host = "https://rlsfzdb.market.alicloudapi.com";
        String path = "/face_id/check";
        String method = "POST";
        String appcode = "43d3b6f4e58b453cbfeb515be1ca52a6";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("idcard", writeEdNumber.getText().toString());
        Bitmap bitmap = BitmapFactory.decodeFile(images.get(0).getCompressPath());
        String base64Str = bitmapToBase64(bitmap);
        bodys.put("image", base64Str);
        bodys.put("name", writeEdName.getText().toString());

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            new Thread(() -> {
                HttpResponse response = doPost(host, path, method, headers, querys, bodys);
                try {
                    String data = EntityUtils.toString(response.getEntity());
                    if (BuildConfig.DEBUG) {
                        Log.e("实名认证", data + "");
                    }
                    FaceCheckResult faceCheckResult = JSON.parseObject(data, FaceCheckResult.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (faceCheckResult != null && faceCheckResult.getData() != null) {
                                ToastUtils.showShort(faceCheckResult.getData().getDescription() + "");
                            }
                            if ("0".equals(faceCheckResult.getCode()) && faceCheckResult.getData() != null && faceCheckResult.getData().getDetail() != null && faceCheckResult.getData().getDetail().getScore() >= 0.45f) {

                                mPresenter.saveRealName(faceCheckResult.getCode(), faceCheckResult.getData().getDetail().getResultCode() + "", writeEdName.getText().toString(), writeEdNumber.getText().toString());
                            } else {
                                hideLoadingDialog();
                            }
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLoadSuccess(String data) {
        hideLoadingDialog();
        ToastUtils.showShort("认证成功");
        Intent intent = new Intent(mActivity, PersonalRealNameSucceedAc.class);
        intent.putExtra("name", writeEdName.getText().toString());
        intent.putExtra("number", writeEdNumber.getText().toString());
        startActivity(intent);
        finish();
    }

    @Override
    public void onLoadFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort(msg);
    }

    @Override
    public void onLoadRealNameSuccess(RealNameResultBean data) {
        hideLoadingDialog();
        if (data != null) {
            if (!TextUtils.isEmpty(data.getIdentityCardName())) {
                writeEdName.setText(data.getIdentityCardName());
            }
            if (!TextUtils.isEmpty(data.getIdentityCardNo())) {
                writeEdNumber.setText(data.getIdentityCardNo());
            }
        }
    }

    @Override
    public void onLoadRealNameFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort(msg + "");
    }
}
